<template>
    <!-- 操作按钮 -->
    <el-button type="primary" style="margin-bottom: 10px" @click="addCategory">+新增分类</el-button>

    <!-- 表格展示 -->
    <el-table v-loading="loading" :data="categoryList" style="width: 100%">
      <el-table-column type="index" label="序号" width="100" />
      <el-table-column prop="name" label="分类名称" />
      <el-table-column prop="sort" label="排序" />
      <el-table-column prop="updateTime" label="更新时间" />

      <!-- 操作列 -->
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <!-- 编辑按钮 -->
          <el-button type="primary" @click="editCategory(row)">
            <el-icon><Edit /></el-icon>
          </el-button>

          <!-- 删除确认框 -->
          <el-popconfirm
            title="确认删除吗?"
            confirm-button-text="确认"
            cancel-button-text="取消"
            @confirm="deleCategory(row.id)"
          >
            <template #reference>
              <el-button type="danger">
                <el-icon><Delete /></el-icon>
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>

      <!-- 无数据提示 -->
      <template #empty>
        <el-empty description="没有数据"></el-empty>
      </template>
    </el-table>

    <!-- 分类编辑对话框 -->
    <CategoryEdit ref="dialog" @success="onSuccess" />
</template>

<script setup>
// 导入依赖
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import CategoryEdit from "./components/CategoryEdit.vue";
import { getCategoryAPI, deleCategoryAPI } from "@/apis/category.js";

// 响应式数据定义
const categoryList = ref([]);
const loading = ref(false);
const dialog = ref(null);

// 方法定义
// 获取分类列表
const getCategory = async () => {
  loading.value = true;
  const res = await getCategoryAPI();
  categoryList.value = res.data;
  loading.value = false;
};

// 新增分类（打开编辑对话框并传入空对象）
const addCategory = () => {
  dialog.value.open({});
};

// 编辑分类（打开编辑对话框并传入当前行数据）
const editCategory = (row) => {
  dialog.value.open(row);
};

// 删除分类
const deleCategory = async (id) => {
  const res = await deleCategoryAPI(id);
  if (res.code === 1) {
    ElMessage.success("删除成功");
    getCategory();
  }
};

// 编辑对话框成功回调
const onSuccess = () => {
  getCategory();
};

// 生命周期钩子
onMounted(() => {
  getCategory();
});
</script>